package org.mozhu.mboot.admin.system.group.web.controller;

import com.google.common.collect.Lists;
import org.mozhu.mboot.admin.system.group.entity.Group;
import org.mozhu.mboot.admin.system.group.entity.GroupType;
import org.mozhu.mboot.admin.system.group.service.GroupService;
import org.mozhu.mboot.core.data.SearchFilters;
import org.mozhu.mboot.core.data.filter.Operator;
import org.mozhu.mboot.core.data.filter.SearchFilter;
import org.mozhu.mboot.core.web.Select2Response;
import org.mozhu.mboot.core.web.bind.annotation.ControllerDefaults;
import org.mozhu.mboot.core.web.controller.BaseCRUDController;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/system/group")
@Controller
@ControllerDefaults(resourceIdentity = "system:group")
public class GroupController extends BaseCRUDController<Group, Long> {

    protected GroupService getBaseService() {
        return (GroupService) baseService;
    }

    @Override
    protected void setCommonData(Model model) {
        super.setCommonData(model);
        model.addAttribute("types", GroupType.values());
    }

    @RequestMapping(value = "/ajax/select/search", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object selectSearch(@RequestParam(value = "query", defaultValue = "") String query, @RequestParam(value = "page", defaultValue = "1") Integer pageNumber) {
        SearchFilter searchFilter = SearchFilters.createFilter(Lists.newArrayList("name"), Operator.LIKE, query);
        // pageNumber start from 1 in page of select
        PageRequest pageable = PageRequest.of(pageNumber - 1, Select2Response.DEFAULT_SELECT_PAGE_SIZE);
        Page<Group> result = this.getBaseService().findAll(searchFilter, pageable);
        return new Select2Response<>(result);
    }

}